import tkinter as tk
from tkinter import ttk
from PyQt6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                            QLineEdit, QPushButton, QComboBox, QGroupBox, 
                            QFormLayout, QTextEdit, QMessageBox)
from PyQt6.QtCore import Qt
from config.settings import load_config, save_config

class ConfigDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("API配置")
        self.setModal(True)
        self.setMinimumWidth(400)
        
        # 设置对话框样式
        self.setStyleSheet("""
            QDialog {
                background-color: #f5f5f5;
            }
            QLabel {
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                color: #333333;
            }
            QLineEdit {
                padding: 6px;
                border: 1px solid #E0E0E0;
                border-radius: 4px;
                background-color: white;
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
            }
            QLineEdit:focus {
                border-color: #0078D4;
            }
            QPushButton {
                background-color: #0078D4;
                color: white;
                border: none;
                padding: 8px 16px;
                border-radius: 4px;
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                min-width: 80px;
            }
            QPushButton:hover {
                background-color: #106EBE;
            }
            QPushButton:pressed {
                background-color: #005A9E;
            }
            QGroupBox {
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                border: 1px solid #E0E0E0;
                border-radius: 4px;
                margin-top: 12px;
                padding-top: 16px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                subcontrol-position: top center;
                padding: 0 5px;
                color: #333333;
            }
            QComboBox {
                padding: 6px;
                border: 1px solid #E0E0E0;
                border-radius: 4px;
                background-color: white;
                font-family: "Microsoft YaHei UI";
                font-size: 12px;
                min-width: 120px;
                color: #333333;
            }
            QComboBox:focus {
                border-color: #0078D4;
            }
            QComboBox QAbstractItemView {
                background-color: white;
                color: #333333;
                border: 1px solid #E0E0E0;
                selection-background-color: #0078D4;
                selection-color: white;
            }
        """)
        
        layout = QVBoxLayout()
        layout.setSpacing(10)
        layout.setContentsMargins(20, 20, 20, 20)
        
        # API选择
        api_select_layout = QHBoxLayout()
        api_select_layout.setSpacing(10)
        api_select_label = QLabel("选择翻译API:")
        self.api_select = QComboBox()
        self.api_select.addItems(["deepseek-chat", "百度翻译", "腾讯翻译", "阿里翻译"])
        self.api_select.currentTextChanged.connect(self.on_api_changed)
        api_select_layout.addWidget(api_select_label)
        api_select_layout.addWidget(self.api_select)
        
        # OCR服务选择
        ocr_select_layout = QHBoxLayout()
        ocr_select_layout.setSpacing(10)
        ocr_select_label = QLabel("选择OCR(文字识别引擎)服务:")
        self.ocr_select = QComboBox()
        self.ocr_select.addItems(["本地OCR", "腾讯OCR", "百度OCR"])
        self.ocr_select.currentTextChanged.connect(self.on_ocr_changed)
        ocr_select_layout.addWidget(ocr_select_label)
        ocr_select_layout.addWidget(self.ocr_select)
        
        # deepseek-chat配置组
        self.deepseek_group = QGroupBox("deepseek-chat配置")
        deepseek_layout = QFormLayout()
        deepseek_layout.setSpacing(10)
        deepseek_layout.setContentsMargins(15, 15, 15, 15)
        self.deepseek_api_key = QLineEdit()
        self.deepseek_api_key.setEchoMode(QLineEdit.EchoMode.Password)
        deepseek_layout.addRow("API密钥:", self.deepseek_api_key)
        
        # 添加deepseek-chat提示词配置
        self.deepseek_prompt = QTextEdit()
        self.deepseek_prompt.setPlaceholderText("请输入deepseek-chat的系统提示词，例如：你是一个专业的翻译助手，请将以下文本翻译成中文：")
        self.deepseek_prompt.setFixedHeight(80)
        deepseek_layout.addRow("提示词(prompt):", self.deepseek_prompt)
        
        self.deepseek_group.setLayout(deepseek_layout)
        
        # 百度翻译配置组
        self.baidu_group = QGroupBox("百度翻译配置")
        baidu_layout = QFormLayout()
        baidu_layout.setSpacing(10)
        baidu_layout.setContentsMargins(15, 15, 15, 15)
        self.baidu_app_id = QLineEdit()
        self.baidu_app_key = QLineEdit()
        self.baidu_app_key.setEchoMode(QLineEdit.EchoMode.Password)
        baidu_layout.addRow("APP ID:", self.baidu_app_id)
        baidu_layout.addRow("密钥:", self.baidu_app_key)
        self.baidu_group.setLayout(baidu_layout)
        
        # 腾讯翻译配置组
        self.tencent_group = QGroupBox("腾讯翻译配置")
        tencent_layout = QFormLayout()
        tencent_layout.setSpacing(10)
        tencent_layout.setContentsMargins(15, 15, 15, 15)
        self.tencent_secret_id = QLineEdit()
        self.tencent_secret_key = QLineEdit()
        self.tencent_secret_key.setEchoMode(QLineEdit.EchoMode.Password)
        tencent_layout.addRow("SecretId:", self.tencent_secret_id)
        tencent_layout.addRow("SecretKey:", self.tencent_secret_key)
        self.tencent_group.setLayout(tencent_layout)
        
        # 阿里翻译配置组
        self.aliyun_group = QGroupBox("阿里翻译配置")
        aliyun_layout = QFormLayout()
        aliyun_layout.setSpacing(10)
        aliyun_layout.setContentsMargins(15, 15, 15, 15)
        self.aliyun_access_key = QLineEdit()
        self.aliyun_access_secret = QLineEdit()
        self.aliyun_access_secret.setEchoMode(QLineEdit.EchoMode.Password)
        aliyun_layout.addRow("AccessId:", self.aliyun_access_key)
        aliyun_layout.addRow("AccessSecret:", self.aliyun_access_secret)
        self.aliyun_group.setLayout(aliyun_layout)
        
        # 腾讯OCR配置组
        self.tencent_ocr_group = QGroupBox("腾讯OCR配置")
        tencent_ocr_layout = QFormLayout()
        tencent_ocr_layout.setSpacing(10)
        tencent_ocr_layout.setContentsMargins(15, 15, 15, 15)
        self.tencent_ocr_secret_id = QLineEdit()
        self.tencent_ocr_secret_key = QLineEdit()
        self.tencent_ocr_secret_key.setEchoMode(QLineEdit.EchoMode.Password)
        tencent_ocr_layout.addRow("SecretId:", self.tencent_ocr_secret_id)
        tencent_ocr_layout.addRow("SecretKey:", self.tencent_ocr_secret_key)
        self.tencent_ocr_group.setLayout(tencent_ocr_layout)
        
        # 百度OCR配置组
        self.baidu_ocr_group = QGroupBox("百度OCR配置")
        baidu_ocr_layout = QFormLayout()
        baidu_ocr_layout.setSpacing(10)
        baidu_ocr_layout.setContentsMargins(15, 15, 15, 15)
        self.baidu_ocr_app_id = QLineEdit()
        self.baidu_ocr_app_key = QLineEdit()
        self.baidu_ocr_app_key.setEchoMode(QLineEdit.EchoMode.Password)
        baidu_ocr_layout.addRow("API Key:", self.baidu_ocr_app_id)
        baidu_ocr_layout.addRow("密钥:", self.baidu_ocr_app_key)
        self.baidu_ocr_group.setLayout(baidu_ocr_layout)
        
        # 保存按钮
        save_btn = QPushButton("保存")
        save_btn.clicked.connect(self.save_config)
        
        layout.addLayout(api_select_layout)
        layout.addLayout(ocr_select_layout)
        layout.addWidget(self.deepseek_group)
        layout.addWidget(self.baidu_group)
        layout.addWidget(self.tencent_group)
        layout.addWidget(self.aliyun_group)
        layout.addWidget(self.tencent_ocr_group)
        layout.addWidget(self.baidu_ocr_group)
        layout.addWidget(save_btn)
        
        self.setLayout(layout)
        
        # 初始时隐藏所有配置组
        self.deepseek_group.hide()
        self.baidu_group.hide()
        self.tencent_group.hide()
        self.aliyun_group.hide()
        self.tencent_ocr_group.hide()
        self.baidu_ocr_group.hide()
        
        # 加载现有配置
        self.load_config()
        
        # 根据当前选择的API显示对应的配置组
        self.on_api_changed(self.api_select.currentText())
        
        # 根据当前选择的OCR服务显示对应的配置组
        self.on_ocr_changed(self.ocr_select.currentText())
        
    def on_api_changed(self, api_name):
        """API选择改变时的处理"""
        self.deepseek_group.setVisible(api_name == "deepseek-chat")
        self.baidu_group.setVisible(api_name == "百度翻译")
        self.tencent_group.setVisible(api_name == "腾讯翻译")
        self.aliyun_group.setVisible(api_name == "阿里翻译")
        
    def on_ocr_changed(self, ocr_name):
        """OCR服务选择改变时的处理"""
        self.tencent_ocr_group.setVisible(ocr_name == "腾讯OCR")
        self.baidu_ocr_group.setVisible(ocr_name == "百度OCR")
        
    def load_config(self):
        """加载配置"""
        config = load_config()
        
        # 设置当前选择的API
        selected_api = config.get('selected_api', 'deepseek')
        api_mapping = {
            'deepseek': "deepseek-chat",
            'baidu': "百度翻译",
            'tencent': "腾讯翻译",
            'aliyun': "阿里翻译"
        }
        self.api_select.setCurrentText(api_mapping.get(selected_api, "deepseek-chat"))
        
        # 设置当前选择的OCR服务
        selected_ocr = config.get('selected_ocr', 'local')
        ocr_mapping = {
            'local': "本地OCR",
            'tencent': "腾讯OCR",
            'baidu': "百度OCR"
        }
        self.ocr_select.setCurrentText(ocr_mapping.get(selected_ocr, "本地OCR"))
        
        # 加载deepseek-chat配置
        deepseek_config = config.get('deepseek', {})
        self.deepseek_api_key.setText(deepseek_config.get('api_key', ''))
        self.deepseek_prompt.setText(deepseek_config.get('prompt', '你是一个专业的翻译助手，请将以下文本翻译成中文：'))
        
        # 加载百度翻译配置
        baidu_config = config.get('baidu', {})
        self.baidu_app_id.setText(baidu_config.get('app_id', ''))
        self.baidu_app_key.setText(baidu_config.get('app_key', ''))
        
        # 加载腾讯翻译配置
        tencent_config = config.get('tencent', {})
        self.tencent_secret_id.setText(tencent_config.get('secret_id', ''))
        self.tencent_secret_key.setText(tencent_config.get('secret_key', ''))
        
        # 加载阿里翻译配置
        aliyun_config = config.get('aliyun', {})
        self.aliyun_access_key.setText(aliyun_config.get('access_key', ''))
        self.aliyun_access_secret.setText(aliyun_config.get('access_secret', ''))
        
        # 加载OCR服务配置
        ocr_services_config = config.get('ocr_services', {})
        
        # 加载腾讯OCR配置
        tencent_ocr_config = ocr_services_config.get('tencent', {})
        self.tencent_ocr_secret_id.setText(tencent_ocr_config.get('secret_id', ''))
        self.tencent_ocr_secret_key.setText(tencent_ocr_config.get('secret_key', ''))
        
        # 加载百度OCR配置
        baidu_ocr_config = ocr_services_config.get('baidu', {})
        self.baidu_ocr_app_id.setText(baidu_ocr_config.get('app_id', ''))
        self.baidu_ocr_app_key.setText(baidu_ocr_config.get('app_key', ''))
        
    def save_config(self):
        """保存配置"""
        api_mapping = {
            "deepseek-chat": 'deepseek',
            "百度翻译": 'baidu',
            "腾讯翻译": 'tencent',
            "阿里翻译": 'aliyun'
        }
        
        ocr_mapping = {
            "本地OCR": 'local',
            "腾讯OCR": 'tencent',
            "百度OCR": 'baidu'
        }
        
        config = {
            'selected_api': api_mapping.get(self.api_select.currentText(), 'deepseek'),
            'selected_ocr': ocr_mapping.get(self.ocr_select.currentText(), 'local'),
            'deepseek': {
                'api_key': self.deepseek_api_key.text(),
                'api_url': 'https://api.deepseek.com/v1/chat/completions',
                'prompt': self.deepseek_prompt.toPlainText()
            },
            'baidu': {
                'app_id': self.baidu_app_id.text(),
                'app_key': self.baidu_app_key.text(),
                'api_url': 'https://fanyi-api.baidu.com/api/trans/vip/translate'
            },
            'tencent': {
                'secret_id': self.tencent_secret_id.text(),
                'secret_key': self.tencent_secret_key.text(),
                'api_url': 'https://tmt.tencentcloudapi.com'
            },
            'aliyun': {
                'access_key': self.aliyun_access_key.text(),
                'access_secret': self.aliyun_access_secret.text(),
                'api_url': 'https://mt.aliyuncs.com'
            },
            'ocr_services': {
                'tencent': {
                    'secret_id': self.tencent_ocr_secret_id.text(),
                    'secret_key': self.tencent_ocr_secret_key.text(),
                    'api_url': 'https://ocr.tencentcloudapi.com'
                },
                'baidu': {
                    'app_id': self.baidu_ocr_app_id.text(),
                    'app_key': self.baidu_ocr_app_key.text(),
                    'api_url': 'https://aip.baidubce.com/rest/2.0/ocr/v1'
                }
            }
        }
        
        try:
            save_config(config)
            QMessageBox.information(self, "成功", "配置已保存")
            self.accept()
        except Exception as e:
            QMessageBox.critical(self, "错误", f"保存配置失败: {str(e)}") 